
package net.vinote.smart.platform.service.action;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.List;

import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.database.tool.Column;
import net.vinote.smart.platform.module.database.tool.DBTool;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.util.AutoInjection;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;


/**
 * 表对象Action类
 * 
 * @author 郑俊伟
 */
public class TableObjectAction
{
	@AutoInjection
	private String tableName;

	@AutoInjection
	private String fieldName;

	/**
	 * 全量刷新表字段<br/>
	 * step1:delete table table_object;<br/>
	 * step2:load all tables of current database;<br/>
	 * step3:insert columns data into table_object;<br/>
	 * 
	 * @throws SQLException
	 */
	@Permission(PermissionEnum.SMART_ADMINISTRATOR)
	public String refreshAllTable(DBTransaction tx) throws SQLException
	{
		DBTool tool = new DBTool(tx.getConn());
		List<String> tableList = tool.getTables();
		DBManager bm = DBManagerFactory.getInstance("table_object");
		tx.join(bm);
		bm.delete(null);// 清除表数据
		for (String table : tableList)
		{
			List<Column> columnList = tool.getColumns(table);
			DecimalFormat format = new DecimalFormat("0000");
			int i = 10;
			for (Column column : columnList)
			{
				BizObject bo = new BizObject();
				bo.setAttribute("TABLENAME", table.toUpperCase());// 表名
				bo.setAttribute("FIELDNAME", column.getName().toUpperCase());// 列名
				bo.setAttribute("ISKEY",
						column.isPrimaryKey() ? PlatformConst.YES
								: PlatformConst.NO);// 是否主键
				bo.setAttribute("DATATYPE",
						String.valueOf(column.getDataType()));
				bo.setAttribute("COLREMARK", column.getRemarks());// 描述列的注释
				// 设置排序号
				bo.setAttribute("SORTNO", format.format(i));
				i += 10;
				bm.saveBizObject(bo);
			}
		}
		return SRE.getInstance().initializ() ? PlatformConst.SUCCESS
				: PlatformConst.FAIL;
	}

}
